<template>
  <view class="component-container" v-if="orderForMapShow">
    <view class="order-info">
      <view class="shop">
        <image :src="orderForMapShow?.shopForUserOrderMap.logo" class="logo" />
        <view class="shop-info">
          <p class="shop-info-row1">
            <span class="shop-name">{{ orderForMapShow?.shopForUserOrderMap.name }}</span>
            <span class="order-detail" @click="openOrderDetails(orderForMapShow!.id)"
              >订单详情 <uni-icons custom-prefix="iconfont" type="icon-detail" size="11" color="#fff"></uni-icons
            ></span>
            <image
              src="@/static/image/evaluate/strike.svg"
              class="call-phone"
              @click="callPhone(orderForMapShow!.shopForUserOrderMap.phone)"
            />
          </p>
          <p class="shop-address">
            {{ orderForMapShow!.shopForUserOrderMap.address }}
          </p>
        </view>
      </view>
      <view class="delivery-info">
        <template
          v-if="
            orderForMapShow?.receivingMethod === ReceivingMethod.DELIVERY &&
            orderForMapShow?.deliveryOrderForUserOrderMap &&
            orderForMapShow?.deliveryOrderForUserOrderMap.riderId
          "
        >
          <image src="@/static/image/evaluate/rider.png" class="rider-avatar" />
          <view class="receiving-address">
            <view class="delivery-info-row1">
              <span class="delivery-state">{{
                orderForMapShow?.deliveryOrderForUserOrderMap?.deliveryState
                  ? deliveryOrderStateLabelOf(orderForMapShow.deliveryOrderForUserOrderMap.deliveryState)
                  : '-'
              }}</span>
              <span class="estimated-delivery-time"
                >预计{{
                  orderForMapShow?.estimatedDeliveryTime
                    ? formatDateTime(orderForMapShow?.estimatedDeliveryTime, 'HH:mm')
                    : '-'
                }}分送达</span
              >
              <image
                src="@/static/image/evaluate/strike.svg"
                class="call-phone"
                @click="callPhone(orderForMapShow!.deliveryOrderForUserOrderMap.riderPhone)"
              />
            </view>
            <span class="sent-to">送至 {{ orderForMapShow?.deliveryAddress }}</span>
          </view>
        </template>
        <template v-else>
          <span class="wait-for-acceptance">
            <span
              v-if="
                ReceivingMethod.SELF_PICKUP === orderForMapShow.receivingMethod &&
                OrderState.ORDER_ACCEPTED === orderForMapShow.state
              "
              class="goto-shop"
              @click="
                invokeMapNavigation({
                  address: orderForMapShow!.shopForUserOrderMap.address,
                  lat: orderForMapShow!.shopForUserOrderMap.latitude,
                  lng: orderForMapShow!.shopForUserOrderMap.longitude
                })
              "
              >导航去商家&nbsp;<uni-icons type="paperplane-filled" size="25rpx" color="#fff"></uni-icons>
            </span>
            <span v-else>等待{{ orderForMapShow?.state === OrderState.ORDER_ACCEPTED ? '骑手' : '商家' }}接单</span>
          </span>
        </template>
      </view>
    </view>
    <view class="operation" v-if="orderForMapShow?.orderCount > 1" @click="emit('switch')">
      <span><uni-icons custom-prefix="iconfont" type="icon-qiehuan"></uni-icons>切换</span>
      <span class="order-count">{{ orderForMapShow?.orderCount ?? 0 }}</span>
    </view>
  </view>
</template>

<script setup lang="ts">
import $API from '@/api'
import { computed, ref } from 'vue'
import { OrderForMapShow } from '@/types/response/order'
import { onMounted } from 'vue'
import { formatDateTime } from '@/utils/TimeUtils'
import { deliveryOrderStateLabelOf } from '@/enum/DeliveryOrderState'
import $store from '@/store'
import { SSEMessageType } from '@/enum/SSEMessageType'
import { SSEConnection } from '@/utils/SSE'
import { RiderLocation } from '@/types/response/user-sse'
import invokeMapNavigation from '@/helper/toMap'
import { ReceivingMethod } from '@/enum/ReceivingMethod'
import { OrderState } from '@/enum/OrderState'
const orderForMapShow = ref<OrderForMapShow>()

async function refreshOrderInfo(shopId?: number) {
  const result = await $API.order.getOrderForMapShow(shopId)
  if (result.success) {
    orderForMapShow.value = result.data
  }
}

onMounted(() => {
  refreshOrderInfo()
})
const emit = defineEmits<{
  (e: 'switch'): void
}>()
// 监听下单后事件，刷新
$store.order.placeOrderEvent.on(() => refreshOrderInfo())
new SSEConnection({ path: '/order/sse/user/on' })
  .onOpen(() => console.log('open success!'))
  .subscriber((subscriber) => {
    subscriber
      .subscribe<number>(SSEMessageType.ORDER_STATE_CHANGE, (data) => {
        if (data.data === orderForMapShow.value?.id) {
          refreshOrderInfo()
        }
      })
      .subscribe<RiderLocation>(SSEMessageType.RIDER_LOCATION_UPDATE, (result) => {
        if (orderForMapShow.value?.deliveryOrderForUserOrderMap.riderId === result.data.riderId) {
          // 骑手位置刷新
          orderForMapShow.value.riderLocation = result.data
          console.log('接收到骑手位置更新', result)
        }
      })
  })
  .onClose(() => console.log('sse close'))
  .start()

// 打开订单详情
function openOrderDetails(orderId: number) {
  uni.navigateTo({ url: `/pages/order-pages/order-detail/index?orderId=${orderId}` })
}
// 切换新的orderId
function switchOrder(orderId: number) {
  refreshOrderInfo(orderId)
}
function callPhone(phoneNumber: string) {
  uni.makePhoneCall({
    phoneNumber
  })
}
defineExpose({
  orderForMapShow,
  id: computed(() => orderForMapShow.value?.id),
  switchOrder
})
</script>

<style scoped lang="scss">
.call-phone {
  width: 30rpx;
  height: 30rpx;
}

.component-container {
  $container-margin-size: 25rpx;

  position: fixed;
  bottom: 0;
  display: flex;
  overflow: hidden;
  margin-bottom: $container-margin-size;
  padding: 30rpx;
  width: 750rpx - ($container-margin-size * 2);
  border-radius: 30rpx;
  background-color: #fff;
  transform: translateX($container-margin-size);
  box-sizing: border-box;
  box-shadow: 0 0 5rpx #ccc;

  .order-info {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    height: 100%;

    .shop {
      display: flex;

      .logo {
        display: block;
        overflow: hidden;
        width: 100rpx;
        height: 100rpx;
        border-radius: 10rpx;
      }

      .shop-info {
        display: flex;
        padding: 0 20rpx;
        flex-grow: 1;
        box-sizing: border-box;
        flex-direction: column;
        font-size: 28rpx;

        .shop-info-row1 {
          display: flex;
          align-items: center;

          .shop-name {
            font-size: 35rpx;
            line-height: 50rpx;
          }

          .order-detail {
            margin: 0 15rpx;
            padding: 0 15rpx;
            height: 45rpx;
            font-size: 23rpx;
            border-radius: 10rpx;
            color: #fff;
            background-color: #a0a0a0;
            line-height: 45rpx;
          }
        }

        .shop-address {
          font-size: 27rpx;
        }

        // .receiving-address {
        //   .sent-to {
        //     color: #333;
        //   }
        // }
      }
    }

    .delivery-info {
      $delivery-state-flag-height: 40rpx;

      display: flex;
      margin-top: 25rpx;

      .wait-for-acceptance {
        display: block;
        margin: 0 auto;
        font-size: 30rpx;
        color: #616161;

        .goto-shop {
          padding: 8rpx 20rpx;
          font-size: 25rpx;
          font-weight: bold;
          border-radius: 10rpx;
          color: #fff;
          background-color: #20d66d;
        }
      }

      .rider-avatar {
        display: block;
        overflow: hidden;
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        flex-shrink: 0;
      }

      .receiving-address {
        display: flex;
        padding: 0 20rpx;
        flex-grow: 1;
        box-sizing: border-box;
        flex-direction: column;

        .delivery-info-row1 {
          display: flex;
          align-items: center;

          .delivery-state {
            display: inline-block;
            padding: 0 15rpx;
            height: $delivery-state-flag-height;
            font-size: 23rpx;
            border-radius: 10rpx;
            color: #fff;
            background-color: #00b26a;
            line-height: $delivery-state-flag-height;
          }

          .estimated-delivery-time {
            margin: 0 15rpx;
            font-size: 27rpx;
          }
        }

        .sent-to {
          line-height: 50rpx;
          font-size: 26rpx;
        }
      }
    }
  }

  .operation {
    position: relative;
    display: flex;
    font-size: 25rpx;
    color: #616161;

    .order-count {
      $order-count-flag-height: 30rpx;

      position: absolute;
      top: 0;
      right: 0;
      width: $order-count-flag-height;
      height: $order-count-flag-height;
      font-size: 20rpx;
      font-weight: bold;
      border-radius: 50%;
      text-align: center;
      color: #fff;
      background-color: red;
      line-height: $order-count-flag-height;
      transform: translate(40%, -10%);
      opacity: 0.7;
    }
  }
}
</style>
